﻿using RpcCentral.Collect;
using RpcCentral.Collect.Controller;
using RpcCentral.Collect.Model;
using RpcCentral.Common;
using RpcCentral.DAL;
using RpcCentral.Model;
using RpcCentral.Service.Interface;
using RpcHelper;
using RpcModel;
using RpcModel.Model;

namespace RpcCentral.Service.Service
{
    internal class GetServerNodeService : IGetServerNodeService
    {
        private IRpcTokenCollect _TokenCollect;
        private IRpcServerCollect _Server;
        private IServerClientLimitCollect _ClientLimit;
        private IRpcServerStateCollect _RunState;
        private IReduceInRankCollect _ReduceInRank;
        public GetServerNodeService(IRpcTokenCollect token,
            IRpcServerCollect server,
            IReduceInRankCollect reduceInRank,
            IRpcServerStateCollect runState,
            IServerClientLimitCollect clientLimit)
        {
            this._RunState = runState;
            this._ReduceInRank = reduceInRank;
            this._ClientLimit = clientLimit;
            this._Server = server;
            this._TokenCollect = token;
        }
        public ServerConfigInfo Get(GetRemoteServer obj)
        {
            RpcTokenCache token = this._TokenCollect.Get(obj.AccessToken);
            RpcServerController rpcServer = this._Server.GetRpcServer(obj.ServerId);
            RemoteServerModel datum = rpcServer.Server;
            ServerConfigInfo server = datum.ConvertMap<RemoteServerModel, ServerConfigInfo>();
            server.Name = datum.ServerName;
            server.ServerId = rpcServer.ServerId;
            server.Reduce = this._ReduceInRank.GetReduceInRank(token.RpcMerId, rpcServer.ServerId);
            server.ClientLimit = this._ClientLimit.GetClientLimit(token.RpcMerId, rpcServer.ServerId);
            server.IsEnablePipe = _CheckIsEnablePipe(rpcServer, obj.Environment);
            if (datum.RegionId != obj.RegionId)
            {
                server.ServerIp = datum.RemoteIp;
            }
            server.GroupTypeVal = rpcServer.GroupTypeVal;
            return server;
        }
        private bool _CheckIsEnablePipe(RpcServerController server, LocalEnvironment env)
        {
            if (!server.Server.IsEnablePipe || server.Server.ServerMac != env.Mac)
            {
                return false;
            }
            RunEnvironment conEnv = _RunState.GetEnvironments(server.ServerId);
            if (conEnv == null)
            {
                return false;
            }
            return env.RunUserIdentity == conEnv.RunUserIdentity && env.RunIsAdmin == conEnv.RunIsAdmin;
        }
    }
}
